package cn.wx.common.unitofwork.aop;

import cn.wx.common.persistence.web.SpringContext;
import cn.wx.common.unitofwork.entity.BizEvent;
import cn.wx.common.unitofwork.mapper.BizEventMapper;

/**
 * 任务池
 */
public class UnitOfWork {
	
	
	private BizEvent transientEvent;
	
	/**
	 * 记录器id
	 */
	private Long sagaId;

	/**
	 * 流程
	 */
	private String saga;

	/**
	 * 开始时间
	 */
	private Long st_;
	
	/**
	 * 根据命令id获取一个事件日志记录器实例
	 * 
	 * @param commandId
	 * @return
	 */
	public static UnitOfWork getInstance(String saga) {
		UnitOfWork unitOfWork = new UnitOfWork();
		unitOfWork.saga = saga;
		unitOfWork.st_ = System.currentTimeMillis();
		return unitOfWork;
	}

	public void generateEvent(Object payload, String project, String environment) {
		this.transientEvent = new BizEvent(this.sagaId,this.saga, payload, project, environment);
	}
	
	/**
	 * 正常日志处理
	 */
	public Long publish() {
		BizEventMapper bizEventMapper = (BizEventMapper) SpringContext.getBean("bizEventMapper");
		if(transientEvent != null) {
			transientEvent.setConsutime((double)(System.currentTimeMillis() - st_)/1000);
			transientEvent.setConsuOk(true);
			bizEventMapper.insert(transientEvent);
			return transientEvent.getpId();
		}
		return null;
	}
	
	/**
	 * 异常日志更新
	 */
	public void publishThrowing(Long sagaId) {
		BizEventMapper bizEventMapper = (BizEventMapper) SpringContext.getBean("bizEventMapper");
		if(transientEvent == null) {
			transientEvent = new BizEvent();
		}
		transientEvent.setpId(sagaId);
		transientEvent.setConsuOk(false);
		bizEventMapper.updateById(transientEvent);
	}
	
	public Long getSagaId() {
		return sagaId;
	}

	public void setSagaId(Long sagaId) {
		this.sagaId = sagaId;
	}

	public String getSaga() {
		return saga;
	}

	public void setSaga(String saga) {
		this.saga = saga;
	}

	public BizEvent getTransientEvent() {
		return transientEvent;
	}

	public void setTransientEvent(BizEvent transientEvent) {
		this.transientEvent = transientEvent;
	}

	public Long getSt_() {
		return st_;
	}

	public void setSt_(Long st_) {
		this.st_ = st_;
	}

}
